import java.util.ArrayList;
import java.util.List;

public class Solution107 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ans=new ArrayList<>();
        dfs(0,root,ans);
        for (int l=0,r=ans.size()-1;l<r;l++,r--){
            List<Integer> temp=ans.get(l);
            ans.set(l,ans.get(r));
            ans.set(r,temp);
        }
        return ans;
    }

    private void dfs(int k, TreeNode root, List<List<Integer>> ans) {
        if (root==null){
            return;
        }
        if (ans.size()==k){
            ans.add(new ArrayList<>());
        }
        ans.get(k).add(root.val);
        dfs(k+1,root.left,ans);
        dfs(k+1,root.right,ans);
    }

    public static void main(String[] args) {
        System.out.println(new Solution107().levelOrderBottom(new TreeNode(3,new TreeNode(9),new TreeNode(20,new TreeNode(15),new TreeNode(7)))));
    }
}
